import pandas as pd
import numpy as np


# 全局变量定义 - 方便修改不同文件
# INPUT_FILE_PATH = 'e:/py_test/bcg_back_trade/stock_features_data.csv'
# OUTPUT_FILE_PATH = 'e:/py_test/bcg_back_trade/processed_stock_data.csv'
def manu_mark_process_stock_data(INPUT_FILE_PATH, OUTPUT_FILE_PATH, save_file=False):
    # 尝试读取CSV文件，处理可能的编码问题
    try:
        # 尝试不同的编码读取
        df = pd.read_csv(INPUT_FILE_PATH, encoding='utf-8')
    except UnicodeDecodeError:
        try:
            df = pd.read_csv(INPUT_FILE_PATH, encoding='gbk')
        except:
            # 如果常规编码失败，尝试二进制读取并分析
            import chardet
            with open(INPUT_FILE_PATH, 'rb') as f:
                result = chardet.detect(f.read(10000))
                encoding = result['encoding']
                print(f"检测到编码: {encoding}")
            df = pd.read_csv(INPUT_FILE_PATH, encoding=encoding)

    # 显示数据的前几行，了解数据结构
    print("数据前5行:")
    print(df.head())
    print("\n数据列名:")
    print(df.columns)

    # 如果数据读取成功，实现处理功能
    if not df.empty:
        # 确保按日期排序（从最早日期开始）
        date_column = None
        if 'date' in df.columns:
            date_column = 'date'
            df[date_column] = pd.to_datetime(df[date_column])
            df = df.sort_values(date_column)
        elif 'Date' in df.columns:
            date_column = 'Date'
            df[date_column] = pd.to_datetime(df[date_column])
            df = df.sort_values(date_column)
        
        # 查找high和low列（不区分大小写）
        high_column = None
        low_column = None
        
        for col in df.columns:
            if col.lower() == 'high':
                high_column = col
            elif col.lower() == 'low':
                low_column = col
        
        # 检查是否找到了high和low列
        if high_column and low_column:
            #df 的open,close列缩小1000倍,并保留2位小数
            # if 'Open' in df.columns:
            #     df['Open'] = (df['Open'] / 1000).round(3)
            # if 'Close' in df.columns:
            #     df['Close'] = (df['Close'] / 1000).round(3)
            # if 'High' in df.columns:
            #     df['High'] = (df['High'] / 1000).round(3)
            # if 'Low' in df.columns:
            #     df['Low'] = (df['Low'] / 1000).round(3)
            

            # 保留所有的列数据
            df_filtered = df.copy()
            
            
            # 使用过去5日和未来5日的最值来判断波峰波谷
            # 创建peek列，初始值为0
            df_filtered['peek'] = 0
            # 创建peek_show列，初始值为0
            df_filtered['peek_show'] = 0
            # 将peek列移动到第二列位置
            peek_values = df_filtered['peek']
            df_filtered.drop(columns=['peek'], inplace=True)
            df_filtered.insert(1, 'peek', peek_values)
            # 将peek_show列移动到第三列位置
            peek_show_values = df_filtered['peek_show']
            df_filtered.drop(columns=['peek_show'], inplace=True)
            df_filtered.insert(2, 'peek_show', peek_show_values)
            
            # 定义窗口大小
            window_size = 5
            
            # 检测波峰和波谷
            for i in range(len(df_filtered)):
                # 获取当前high和low值
                current_high = df_filtered.iloc[i][high_column]
                current_low = df_filtered.iloc[i][low_column]
                
                # 定义窗口范围：过去5天和未来5天
                start_idx = max(0, i - window_size)
                end_idx = min(len(df_filtered), i + window_size + 1)  # +1 because end is exclusive
                
                # 获取窗口内的high和low值
                window_highs = df_filtered.iloc[start_idx:end_idx][high_column]
                window_lows = df_filtered.iloc[start_idx:end_idx][low_column]
                
                # 检查是否为波峰（high值在窗口内最大）
                if current_high == window_highs.max() and i > start_idx and i < end_idx - 1:
                    # 标记波峰：high值
                    df_filtered.iloc[i, df_filtered.columns.get_loc('peek_show')] = current_high
                    df_filtered.iloc[i, df_filtered.columns.get_loc('peek')] = 2
                # 检查是否为波谷（low值在窗口内最小）
                elif current_low == window_lows.min() and i > start_idx and i < end_idx - 1:
                    # 标记波谷：low值
                    df_filtered.iloc[i, df_filtered.columns.get_loc('peek_show')] = current_low
                    df_filtered.iloc[i, df_filtered.columns.get_loc('peek')] = 1
            
            # 显示结果的一部分（显示前30行以包含被标记的波峰波谷）
            print("\n处理后的数据（high和low已缩小1000倍，包含peek列）:")
            print(df_filtered.head(30))
            
            # 保存结果
            if save_file:
                df_filtered.to_csv(OUTPUT_FILE_PATH, index=False)
                print(f"\n处理后的数据已保存到 {OUTPUT_FILE_PATH}")
            return  df_filtered,OUTPUT_FILE_PATH
        else:
            print("错误：未找到high和low列")
    else:
        print("无法读取有效数据")